/**
 * 题目详情
 */
<template>
    <el-form v-loading="loading" :model="formData" :rules="type === 'add' || type === 'edit' ? formRules : {}" ref="formRef" label-width="120px" :scroll-to-error="true">
        <vp-card>
            <el-row>
                <vp-col :span="showSameQuestion ? 2: 1">
                    <el-row>
                        <vp-col :span="1">
                            <el-form-item prop="tmbh">
                                <template #label><vp-label zh="题目编号" en="Question No."/></template>
                                <el-input v-model="formData.tmbh" v-if="type === 'add' || type === 'edit'" v-trim maxlength="50">
                                </el-input>
                                <span v-else>{{ formData.tmbh }}</span>
                            </el-form-item>
                        </vp-col>
                        <vp-col :span="1">
                            <el-form-item prop="tmlx">
                                <template #label><vp-label zh="题目类型" en="Type"/></template>
                                <el-radio-group 
                                    v-model="formData.tmlx" 
                                    @change="handleChangeQuestionType" 
                                    v-if="type === 'add' || type === 'edit'"
                                >
                                    <el-radio :value="10"><vp-label zh="单选题" en="Single Selection"/></el-radio>
                                    <el-radio :value="30"><vp-label zh="多选题" en="Multiple Selection"/></el-radio>
                                    <el-radio :value="15"><vp-label zh="判断题" en="True-False"/></el-radio>
                                </el-radio-group>
                                <span v-else>{{ formData.tmlx === 10 ? '单选' : formData.tmlx === 30 ? '多选' : formData.tmlx === 15 ? '判断' : '' }}</span>
                            </el-form-item>
                        </vp-col>
                        <vp-col :span="1">
                            <el-form-item prop="tkidList">
                                <template #label><vp-label zh="所属题库" en="Affiliated Bank"/></template>
                                <QuestionBankMultSelect
                                    v-model="formData.tkidList"
                                    class="w100"
                                    v-if="type === 'add' || type === 'edit'"
                                />
                                <span v-else>{{formData.tkmc}}</span>
                            </el-form-item>
                        </vp-col>
                    </el-row>
                    <vp-card>
                        <template #header>
                            <vp-label zh="题干" en="Question Stem"/>
                        </template>
                        <el-row>
                            <vp-col :span="1">
                                <el-form-item prop="tgms">
                                    <template #label><vp-label zh="文字描述" en="Text Description"/></template>
                                    <el-input 
                                        type="textarea" 
                                        v-model="formData.tgms" 
                                        v-trim 
                                        maxlength="1000" 
                                        rows="3" 
                                        @change="handleChangeQuestionStem" 
                                        @input="handleSearchSameQuestion(1)"
                                        v-if="type == 'add' || type == 'edit'"
                                    />
                                    <span v-else>{{ formData.tgms }}</span>
                                </el-form-item>
                            </vp-col>
                            <vp-col :span="1" v-if="type !== 'view' || formData.questionImages.length > 0">
                                <el-form-item>
                                    <template #label><vp-label zh="图片" en="Picture"/></template>
                                    <VpImageUpload 
                                        v-model="formData.questionImages" 
                                        @change="handleChangeQuestionStem" 
                                        :disabled="type === 'view'"
                                    />
                                </el-form-item>
                            </vp-col>
                            <vp-col :span="1" v-if="type !== 'view' || formData.questionVideos.length > 0">
                                <el-form-item>
                                    <template #label><vp-label zh="视频/音频" en="Video/Audio"/></template>
                                    <VpVideoUpload 
                                        v-model="formData.questionVideos" 
                                        @change="handleChangeQuestionStem"
                                        :disabled="type === 'view'"
                                    />
                                </el-form-item>
                            </vp-col>
                        </el-row>
                    </vp-card>
                    <vp-card>
                        <template #header>
                            <vp-label zh="选项" en="Choice"/>
                            <el-input-number class="ml16" 
                                v-model="formData.xxsl" 
                                :min="2" 
                                :max="10" 
                                @change="handleAnswerCountChange" 
                                v-if="type === 'add' || type === 'edit'"
                            />
                        </template>
                        <div v-for="(answer,index) in formData.answers">
                            <el-row>
                                <vp-col :span="1">
                                    <vp-label :zh="`选项${index+1}`" :en="`Choice${index+1}`" />
                                </vp-col>
                            </el-row>
                            <el-row>    
                                <vp-col :span="1">
                                    <el-form-item :prop="`answers[${index}]`" :rules="type === 'add' || type === 'edit' ? formRules.xxxq : []">
                                        <template #label><vp-label zh="描述" en="Description"/></template>
                                        <el-input 
                                            type="textarea" 
                                            v-model="answer.ms" 
                                            v-trim maxlength="1000" 
                                            rows="3" 
                                            @input="handleSearchSameQuestion(1)"
                                            v-if="type == 'add' || type == 'edit'"
                                        />
                                        <span v-else>{{ answer.ms }}</span>
                                    </el-form-item>
                                </vp-col>
                            </el-row>
                            <el-row>
                                <vp-col :span="2">
                                    <el-form-item prop="zqxxbs">
                                        <el-checkbox 
                                            v-model="answer.zqxxbs" 
                                            :true-value="1" 
                                            :false-value="0" 
                                            @change="handleChangeCorrectAnswer(answer)"
                                            v-if="type == 'add' || type == 'edit'"
                                        >
                                            <vp-label zh="正确选项" en="Correct Option"/>
                                        </el-checkbox>
                                    </el-form-item>
                                </vp-col>
                                <vp-col :span="2">
                                    <el-form-item prop="gdwzbs">
                                        <el-checkbox 
                                            v-model="answer.gdwzbs" 
                                            :true-value="1" 
                                            :false-value="0" 
                                            v-if="type == 'add' || type == 'edit'"
                                        >
                                            <vp-label zh="固定位置" en="Fixed Position"/>
                                        </el-checkbox>
                                    </el-form-item>
                                </vp-col>
                                <vp-col :span="2" v-if="type == 'view'">
                                    <el-form-item>
                                        <el-space>
                                            <el-tag size="large" type="success" v-if="answer.zqxxbs === 1">
                                                <vp-label zh="正确选项" en="Correct Option"/>
                                            </el-tag>
                                            <el-tag size="large" type="success"  v-if="answer.gdwzbs === 1">
                                                <vp-label zh="固定位置" en="Fixed Position"/>
                                            </el-tag>
                                        </el-space>
                                    </el-form-item>
                                </vp-col>
                            </el-row>
                            <el-row  v-if="type !== 'view' || answer?.images?.length > 0">
                                <vp-col :span="1">
                                    <el-form-item>
                                        <template #label><vp-label zh="图片" en="Picture"/></template>
                                        <VpImageUpload 
                                            v-model="answer.images" 
                                            @change="handleChangeQuestionAnswer(index)"
                                            :disabled="type === 'view'"
                                        />
                                    </el-form-item>
                                </vp-col>
                            </el-row>
                            <el-divider />
                        </div>
                    </vp-card>
                </vp-col>
                <vp-col :span="2" v-if="showSameQuestion">
                    <el-row style="margin: 40px 80px;">
                        <vp-col :span="1">
                            <el-input
                                v-model="sameKeyword"
                                size="large"
                                @input="handleSearchSameQuestion(2)"
                                placeholder="关键字搜索题干和答案/Search for the question stem and answers by keywords"
                            >
                            <template #append>
                                <el-button @click="handleSearchSameQuestion(2)"><SvgIcon name="ele-Search" /></el-button>
                            </template>
                            </el-input>
                        </vp-col>
                        <vp-col :span="1" v-if="sameQuestionCount === 0">
                            <p>
                                <span v-if="sameQuestionType === 1">
                                    <vp-label zh="不错，没有找到与题干/答案相同的题目。" en="Good, no identical questions with the question stem/answer were found."/>
                                </span>
                                <span v-else>
                                    <vp-label :zh="`不错，没有找到与${ sameKeyword }相关的题目。`" :en="`Good, no questions related to ${ sameKeyword } were found.`"/>
                                </span>
                            </p>
                        </vp-col>
                        <vp-col :span="1" v-if="sameQuestionCount > 0">
                            <div v-for="(question, i) in sameQuestions" class="pb16">
                                <el-divider content-position="left"><vp-label :zh="`问题${i+1}`" :en="`Question${i+1}`"/></el-divider>
                                <div class="pb8"> 
                                    <el-text size="large">
                                        <span>{{ i + 1 }}. </span>
                                        <span v-html="markTextColor(searcSamehKeyword, question.tgms || '非文字题')"></span>
                                    </el-text>
                                </div>
                                <div>
                                    <div v-for="(answer, num) in question.answers" class="pt2 pb2">
                                        <el-text>
                                            <span>{{ String.fromCharCode(num + 65)  }}: </span>
                                            <span v-html="markTextColor(searcSamehKeyword, answer.ms || '非文字答案')"></span>
                                        </el-text>
                                    </div>
                                </div>
                            </div>
                            <el-divider v-if="sameQuestionCount > sameQuestionSize">
                                <el-text type="info">
                                    <vp-label :zh="`最多显示${sameQuestionSize}条相同的题目`" :en="`Display up to ${sameQuestionSize} identical questions at most.`"/>
                                </el-text>
                            </el-divider>
                        </vp-col>
                    </el-row>
                </vp-col>
            </el-row>
        </vp-card>
    </el-form>
</template>
<script setup lang="ts" name="examQuestion">
import { onMounted, ref, computed } from 'vue';
import validateUtils from '/@/utils/validateUtils';
import VpImageUpload from '/@/components/vp/image/VpImageUpload.vue';
import VpVideoUpload from '/@/components/vp/video/VpVideoUpload.vue';
import { ElMessage } from "element-plus";
import { debounce } from 'lodash';
import request from '/@/utils/request';
import { markTextColor } from '/@/utils/toolsValidate';
import QuestionBankMultSelect from '/@/components/vp/questionBank/QuestionBankMultSelect.vue';

const emits = defineEmits(['formSubmited']);
const props = defineProps<{
    type: string,
    loading: boolean,
}>();
const formData = ref({
    id:"",
    zt:10,
    tmbh:"",
    tmlx:10,
    kczid:"",
    kcid:"",
    kcbh:"",
    kcmc:"",
    kcms:"",
    kcmlbh:"",
    kcmlnr:"",
    tkmc:"",
    tgid:"",
    tgms:"",
    tgfjidTp:"",
    tgfjidSp:"",
    xxsl: 3,
    tkidList: [],
    questionImages: [],
    questionVideos: [],
    answers: [{
        id: "",
        mxlx: 20,
        ms: "",
        fjidTp: "",
        fjidSp: "",
        gdwzbs: null,
        zqxxbs: null,
        images: [],
        videos: [],
    }],
    attachments: [] as any[],
});
const formRules = {
    tmbh:[ validateUtils.notNull, validateUtils.notChinese ],
    tmlx:[ validateUtils.notNull ],
    tkidList: [ validateUtils.notNull ],
    tgms: [{
            required: true,
            validator: (rule: any, value: any, callback: any)=>{
                if(!formData.value.tgms 
                    && formData.value.questionImages.length === 0 
                    && formData.value.questionVideos.length === 0){
                    callback(new Error("文字描述、图片、视频、音频至少输入一项/At least one item must be entered among text description, images, videos, and audio."))
                }
                callback()
            },
        }
    ],
    xxxq: [{
            required: true,
            validator: (rule: any, value: any, callback: any)=>{
                if(!value.ms && value.images.length === 0){
                    callback(new Error("文字和图片至少输入一项/At least one item between text and images must be entered."))
                }
                callback()
            },
        }
    ],
}
const formRef = ref();
const showSameQuestion = ref(true);
const sameKeyword = ref('');
const sameLoading = ref(false);
const sameQuestions = ref([] as any[]);
const sameQuestionCount = ref(0);
const sameQuestionType = ref(1);
const sameQuestionSize = ref(10);

// 清空数据
const initFormData = ()=>{
    formData.value = {
        id:"",
        zt:10,
        tmbh:"",
        tmlx:10,
        kczid:"",
        kcid:"",
        kcbh:"",
        kcmc:"",
        kcms:"",
        kcmlbh:"",
        kcmlnr:"",
        tkmc:"",
        tgid:"",
        tgms:"",
        tgfjidTp:"",
        tgfjidSp:"",
        xxsl: 3,
        tkidList: [],
        questionImages: [],
        questionVideos: [],
        answers: [],
        attachments: [],
    }
}

// 组件挂载后事件
onMounted(()=>{
    if (props.type === 'view') {
        showSameQuestion.value = false;
    }
})

// 回显数据
const setData = (data: any) => {
    initFormData();
    formData.value = {
        ...formData.value,
        ...data,
        tkidList: (data.questionBanks || []).map((bank: any) => {
            return bank.tkid;
        }),
    };
    if (formData.value.id && formData.value.answers && formData.value.answers.length > 0) {
        formData.value.xxsl = formData.value.answers.length;
    }
    handleAnswerCountChange();
}

/**
 * 获取数据
 */
const getData = (): Promise<any>=>{
    return new Promise((resolve, reject) => {
        formRef.value.validate((valid: boolean) => {
            if (valid) {
                const zqxxsl = formData.value.answers.filter((obj: any) => {
                    return obj.zqxxbs === 1;
                }).length;
                if (zqxxsl === 0) {
                    ElMessage.error('正确选项至少有一个/At least one correct option is required.');
                    reject();
                }
                if (formData.value.tmlx !== 30 && zqxxsl > 1) {
                    ElMessage.error('单选题/判断题只能有一个正确答案/For single-choice questions, there can only be one correct answer.');
                    reject();
                }
                resolve(processDataBeforeGetData());
            } else {
                reject();
            }
        })
    })
}

// 获取数据-处理数据
const processDataBeforeGetData = () => {
    const answers = [...formData.value.answers];
    answers.push({
        id: formData.value.tgid,
        mxlx: 10,
        ms: formData.value.tgms,
        fjidTp: formData.value.tgfjidTp,
        fjidSp: formData.value.tgfjidSp,
        images: formData.value.questionImages,
        videos: formData.value.questionVideos,
        gdwzbs: null, 
        zqxxbs: null
    });
    return {
        ...formData.value,
        answers: answers,
        questionBanks: (formData.value.tkidList || []).map((tkid: string) => {
            return {
                tkid: tkid
            }
        })
    }
}

// 当单选/多选发生了改变
const handleChangeQuestionType = () => {
    if (formData.value.tmlx === 15) {
        formData.value.xxsl = 2;
        formData.value.answers[0].ms = '是';
        formData.value.answers[1].ms = '否';
    } else {
        formData.value.xxsl = 3;
    }
    handleAnswerCountChange();
}

// 选项数量改变
const handleAnswerCountChange = () => {
    const currentAnswerCount = formData.value.answers.length;
    const answerCount = formData.value.xxsl;
    if (currentAnswerCount < answerCount) {
        for (let index = 0; index < answerCount - currentAnswerCount; index++) {
            formData.value.answers.push({
                id: "",
                mxlx: 20,
                ms: "",
                fjidTp: "",
                fjidSp: "",
                gdwzbs: 0 as any,
                zqxxbs: 0 as any,
                images: [],
                videos: [],
            });
        }
    } else if (currentAnswerCount > answerCount) {
        formData.value.answers = formData.value.answers.slice(0, answerCount);
    }
}

/**
 * 题干内容改变
 */
const handleChangeQuestionStem = () => {
    formRef.value.validateField('tgms');
}

/**
 * 选项内容改变
 */
const handleChangeQuestionAnswer = (index: number) => {
    formRef.value.validateField(`answers[${index}]`);
}

// 查找相同问题（防抖）
const handleSearchSameQuestion = debounce((type: number) => {
    sameQuestionType.value = type;
    if (searcSamehKeyword.value) {
        sameLoading.value = true;
        request.post('/training/question/sameQuestions', {
            keyword: searcSamehKeyword.value,
            id: formData.value.id,
            pageSize: sameQuestionSize.value,
        }).then(res => {
            sameQuestionCount.value = res?.data?.total;
            sameQuestions.value = res?.data?.list || [];
            console.log(res);
        }).finally(()=>{
            sameLoading.value = false;
        })
    } else {
        sameQuestionCount.value = 0;
        sameQuestions.value = [];
    }
}, 500);

// 获取根据类型判定当前关键字
const searcSamehKeyword = computed(() => {
    let keyword = '';
    const list = []
    if (sameQuestionType.value === 2 && sameKeyword.value) {
        keyword = sameKeyword.value;
    } else {
        const tgms = formData.value.tgms;
        if (tgms) {
            list.push(tgms);
        }
        (formData.value.answers || []).forEach((answer: any) => {
            if (answer.ms) {
                list.push(answer.ms);
            }
        })
        if (list.length > 0) {
            keyword = list.join("@_@");
        }
    }
    return keyword;
});

/**
 * 正确选项改变
 */
const handleChangeCorrectAnswer = (answer: any) => {
    // 单选/判断题选中正确选项时，取消其它正确选项
    if (formData.value.tmlx !== 30 && answer.zqxxbs === 1) {
        formData.value.answers.forEach((obj: any) => {
            if (obj !== answer) {
                obj.zqxxbs = 0;
            }
        })
    }
}

defineExpose({
    setData,
    getData,
})

</script>
